package com.demo.base.duty;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author : YU.TAN
 * @date : 2021/10/28 14:11
 */
@Component("ChainPattern")
public class ChainPattern {

    /**
     * 自动注入各个责任链的对象
     */
    @Autowired
    private List<AbstractHandler> abstractHandlers;

    private AbstractHandler abstractHandler;

    /**
     * spring注入后自动执行，责任链的对象连接起来
     */
    @PostConstruct
    public void init() {

        for (int i = 0; i < abstractHandlers.size(); i++) {
            if (i == 0) {
                abstractHandler = abstractHandlers.get(i);
            } else {
                AbstractHandler currentHandler = abstractHandlers.get(i - 1);
                AbstractHandler nextHandler = abstractHandlers.get(i);
                currentHandler.setNextHandler(nextHandler);
            }
        }
    }

    public Response execute(Request request, Response response) {
        abstractHandler.filter(request, response);
        return response;
    }

    public AbstractHandler getAbstractHandler() {
        return abstractHandler;
    }

    public void setAbstractHandlers(AbstractHandler abstractHandlers) {
        this.abstractHandler = abstractHandlers;
    }

}
